package google.sites.model.commands.attachments;

import com.google.gdata.data.OutOfLineContent;
import com.google.gdata.data.sites.AttachmentEntry;
import com.google.gdata.util.ServiceException;
import dev.tools.design.patterns.command.CommandException;
import google.sites.model.commands.SitesCommand;

import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 04-10-2013
 * Time: 15:38
 */
public class DownloadAttachment extends SitesCommand {
    private String url;
    private AttachmentEntry attachmentEntry;
    private String directory;

    @Override
    protected void protectedExecute() throws CommandException {
        try {
            downloadFile(url, directory + attachmentEntry.getTitle().getPlainText());
        } catch (IOException | ServiceException e) {
            throw new CommandException(e);
        }
    }

    public DownloadAttachment setAttachmentEntry(AttachmentEntry attachmentEntry) {
        this.attachmentEntry = attachmentEntry;
        url = ((OutOfLineContent) attachmentEntry.getContent()).getUri();
        return this;
    }

    public DownloadAttachment setAttachmentEntryId(String entryId) throws IOException, ServiceException {
        return setAttachmentEntry(getService().getEntry(
                new URL(getContentFeedUrl() + entryId), AttachmentEntry.class));
    }

    public DownloadAttachment setDirectory(String directory) {
        this.directory = directory;
        return this;
    }
}
